/* list.c -- functions supporting list operations */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"

static List ListHead;

/* local function prototype */
static void CopyToNode(Item *item, Node * pnode);

/* interface functions   */
/* set the list to empty */
void InitList(void)
{
    ListHead = NULL;
}

/* returns true if list is empty */
bool ListIsEmpty(void)
{
    if (ListHead == NULL)
        return true;
    else
        return false;
}


/* returns number of nodes */
unsigned int ListItemCount(void)
{
    unsigned int count = 0;
    Node * pnode = ListHead;    /* set to start of list */

    while (pnode != NULL)
    {
        ++count;
        pnode = pnode->next;  /* set to next node     */
    }
    
    return count;
} 

/* creates node to hold item and adds it to the end of */
/* the list pointed to by plist (slow implementation)  */
bool AddItem(Item *item)
{
    Node * pnew;
    Node * scan = ListHead;

    pnew = (Node *) malloc(sizeof(Node));
    if (pnew == NULL)
        return false;     /* quit function on failure  */

    CopyToNode(item, pnew);
    pnew->next = NULL;
    if (scan == NULL)          /* empty list, so place */
        ListHead = pnew;         /* pnew at head of list */
    else
    {
        while (scan->next != NULL)
            scan = scan->next;  /* find end of list    */
        scan->next = pnew;      /* add pnew to end     */
    }
   
    return true;
}

/* visit each node and execute function pointed to by pfun */
void Traverse  (void (* pfun)(Item *item) )
{
    Node * pnode = ListHead;    /* set to start of list   */

    while (pnode != NULL)
    {
        (*pfun)(&(pnode->item)); /* apply function to item */
        pnode = pnode->next;  /* advance to next item   */
    }
}

int GetTaskinfoByFilename(Taskinfo *taskinfo, char *filename)
{
    Node * pnode = ListHead;    /* set to start of list   */

    while (pnode != NULL)
    {
        if(0 == strcmp(pnode->item.filename, filename)){
            *taskinfo = pnode->item;
            return 0;
        }
        pnode = pnode->next;  /* advance to next item   */
    }

    return -1;
}

int RemoveListItem(Taskinfo *taskinfo)
{
    return 0;
}

/* free memory allocated by malloc() */
/* set list pointer to NULL          */
void EmptyTheList(void)
{
    Node * psave;

    while (ListHead != NULL)
    {
        psave = (ListHead)->next; /* save address of next node */
        free(ListHead);           /* free current node         */
        ListHead = psave;         /* advance to next node      */
    }
}

/* local function definition  */
/* copies an item into a node */
static void CopyToNode(Item *item, Node * pnode)
{
    pnode->item = *item;  /* structure copy */
}
